//
//  CJCardSwitchFlowLayout.m
//  TSImageFilterDemo
//
//  Created by ciyouzen on 2017/2/25.
//  Copyright © 2017年 dvlproad. All rights reserved.
//

#import "CJCardSwitchFlowLayout.h"

/// layout的初始化方式
typedef NS_ENUM(NSUInteger, CJCardSwitchLayoutInitType) {
    CJCardSwitchLayoutInitTypeScale,
    CJCardSwitchLayoutInitTypeMargin,
};

@interface CJCardSwitchFlowLayout () {
    
}
@property (nonatomic, assign, readonly) CJCardSwitchLayoutInitType initType;    /**< layout的初始化方式 */

@end


@implementation CJCardSwitchFlowLayout


/*
 *  初始化
 *
 *  @param cardWidthScale   居中时候，卡片宽度占据collectionView视图宽度的比例
 *  @param cardHeightScale  居中时候，卡片高度占据collectionView视图高度的比例
 *
 *  @return 布局layout
 */
- (instancetype)initWithCardWidthScale:(CGFloat)cardWidthScale cardHeightScale:(CGFloat)cardHeightScale {
    self = [super init];
    if (self) {
        NSAssert(cardWidthScale > 0.3 && cardHeightScale > 0.3, @"居中时候，卡片宽高占据cell宽高的比例不能太小，否则容易看不到");
        _initType = CJCardSwitchLayoutInitTypeScale;
        _cardWidthScale = cardWidthScale;
        _cardHeightScale = cardHeightScale;
    }
    return self;
}


/*
 *  初始化
 *
 *  @param cardMaginLeft            居中时候，卡片左边缘距离collectionView左侧的距离
 *  @param cardMarginRight          居中时候，卡片右边缘距离collectionView右侧的距离
 *  @param cardMarginTop            居中时候，卡片上边缘距离collectionView上侧的距离
 *  @param cardMarginBottom         居中时候，卡片下边缘距离collectionView下侧的距离
 *
 *  @return 布局layout
 */
- (instancetype)initWithCardMarginLeft:(CGFloat)cardMaginLeft
                       cardMarginRight:(CGFloat)cardMarginRight
                         cardMarginTop:(CGFloat)cardMarginTop
                      cardMarginBottom:(CGFloat)cardMarginBottom
{
    self = [super init];
    if (self) {
        _initType = CJCardSwitchLayoutInitTypeMargin;
        _cardMaginLeft= cardMaginLeft;
        _cardMarginRight = cardMarginRight;
        _cardMarginTop = cardMarginTop;
        _cardMarginBottom = cardMarginBottom;
    }
    return self;
}

//初始化方法
- (void)prepareLayout {
    [super prepareLayout];
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.sectionInset = UIEdgeInsetsMake([self insetY], [self insetX], [self insetY], [self insetX]);
    self.itemSize = CGSizeMake([self itemWidth], [self itemHeight]);
    self.minimumLineSpacing = 5;
}

//设置缩放动画
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    //获取cell的布局
    NSArray *attributesArr = [super layoutAttributesForElementsInRect:rect];
    //屏幕中线
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width/2.0f;
    //最大移动距离，计算范围是移动出屏幕前的距离
    CGFloat maxApart = (self.collectionView.bounds.size.width + [self itemWidth])/2.0f;
    //刷新cell缩放
    NSInteger attributeCount = attributesArr.count;
    for (NSInteger index = 0; index < attributeCount; index++) {
        UICollectionViewLayoutAttributes *attributes = attributesArr[index];
        
        //获取本cell中心和屏幕中心的距离(正数：左侧；0:中心；负数：左侧)
        CGFloat apart = attributes.center.x - centerX;
        //移动进度 -1~0~1
        CGFloat progress = apart/maxApart;
        //在屏幕外的cell不处理
        if (fabs(progress) > 1) {continue;}
        //根据余弦函数，弧度在 -π/4 到 π/4,即 scale在 √2/2~1~√2/2 间变化
        CGFloat scale = fabs(cos(fabs(progress) * M_PI/4));
        //缩放大小
        attributes.transform = CGAffineTransformMakeScale(scale, scale);
        //更新中间位
        CGFloat halfItemWidth = [self itemWidth]/2.0f;
//        if (index == 1) {
//            NSLog(@"index:%zd, progress:%.2f, apart:%.2f, halfItemWidth=%.2f", index, progress, apart, halfItemWidth);
//        }
        
        BOOL isLeftOrCenter = apart <= halfItemWidth; // 是否已经滚动到左边(在中间也算)
        self.progressValueChangeBlock(attributes.indexPath, progress, isLeftOrCenter);
    }
    return attributesArr;
}

#pragma mark -
#pragma mark 配置方法
//卡片宽度
- (CGFloat)itemWidth {
    CGFloat collectionViewWidth = self.collectionView.bounds.size.width;
    
    if (self.initType == CJCardSwitchLayoutInitTypeMargin) {
        CGFloat itemWidth = collectionViewWidth - self.cardMaginLeft - self.cardMarginRight;
        return itemWidth;
    } else {
        CGFloat itemWidth = collectionViewWidth * self.cardWidthScale;
        return itemWidth;
    }
}

- (CGFloat)itemHeight {
    CGFloat collectionViewHeight = self.collectionView.bounds.size.height;
    
    if (self.initType == CJCardSwitchLayoutInitTypeMargin) {
//        CGFloat itemWidth = [self itemWidth];
//        CGFloat itemHeight = itemWidth / self.cardWidthHeightRatio;
//        if (itemHeight > collectionViewHeight) {
//            NSLog(@"计算出来的itemHeight:%.2f不能超过collectionViewHeight:%.2f，所以itemHeight退而去取小", itemHeight, collectionViewHeight);
//            itemHeight = collectionViewHeight;
//        }
        CGFloat itemHeight = collectionViewHeight - self.cardMarginTop - self.cardMarginBottom;
        return itemHeight;
    } else {
        CGFloat itemHeight = collectionViewHeight * self.cardHeightScale;
        return itemHeight;
    }
}

//设置左右缩进
- (CGFloat)insetX {
    CGFloat insetX = (self.collectionView.bounds.size.width - [self itemWidth])/2.0f;
    return insetX;
}

- (CGFloat)insetY {
    CGFloat insetY = (self.collectionView.bounds.size.height - [self itemHeight])/2.0f;
    return insetY;
}

//是否实时刷新布局
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return true;
}

@end
